//
//  MegafaunaOfDayTableViewController.m
//  Digital Seamonsters
//
//  Created by Adam Cue on 2/18/11.
//  Copyright Adam Cue 2011.
//
//  This program is licensed and distributed under the terms of the GNU General Public License.  
//	The text for the license can be found in the license.txt file in this project.
//

#import "MegafaunaOfDayTableViewController.h"
#import "JSON.h"
#import "MFOWMedia.h"
#import "AsyncImageView.h"
#import "MarineFetcher.h"
#import "ListOfMegafaunaOfWeekTableViewCell.h"

@interface MegafaunaOfDayTableViewController (Private)
#pragma mark SetupMethods
- (void)setupListControl;
- (void)setupHeaderView;
#pragma mark HelperMethods
- (void)changeList;
@end

@implementation MegafaunaOfDayTableViewController

@synthesize listOfMegafauna = _listOfMegafauna;
@synthesize savedMegafauna = _savedMegafauna;
@synthesize listControl = _listControl;
@synthesize headerView = _headerView;
@synthesize delegate;


- (id)initWithStyle:(UITableViewStyle)style {
   self = [super initWithStyle:style];
   if (self) {
      allMegafauna = YES;
      [self setupListControl];
		[self setupHeaderView];
		_savedMegafauna = [[NSMutableArray alloc] initWithCapacity:4];
   }
   return self;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
   return interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight;
}

- (void)dealloc {
   self.listOfMegafauna = nil;
   self.savedMegafauna = nil;
   self.listControl = nil;
   self.headerView = nil;
   self.delegate = nil;
   
   [super dealloc];
}

#pragma mark SetupMethods
- (void)setupListControl {
   _listControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"All", @"Favorites", nil]];
   self.listControl.selectedSegmentIndex = 0;
   self.listControl.segmentedControlStyle = UISegmentedControlStyleBar;
   self.listControl.tintColor = [UIColor darkGrayColor];
   [self.listControl addTarget:self action:@selector(changeList) forControlEvents:UIControlEventValueChanged];
   self.listControl.frame = CGRectMake(4, 4, 312, 30);
}

- (void)setupHeaderView {
   _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 38)];
   self.headerView.backgroundColor = [UIColor blackColor];
   [self.headerView addSubview:self.listControl];
}

#pragma mark HelperMethods
- (void)changeList{
	if(self.listControl.selectedSegmentIndex == 0){
		allMegafauna = YES;
	}
	else{
		allMegafauna = NO;
		NSFetchRequest *savedRequest = [[NSFetchRequest alloc] init];
		NSEntityDescription *savedEntity = [NSEntityDescription entityForName:@"MFOW" inManagedObjectContext:[[MarineFetcher sharedInstance] managedObjectContext]];
		[savedRequest setPredicate:[NSPredicate predicateWithFormat:@"isRecent == NO"]];
		[savedRequest setEntity:savedEntity];
		NSError *savedError;
		NSArray *savedFetchResults = [[[MarineFetcher sharedInstance] managedObjectContext] executeFetchRequest:savedRequest error:&savedError];
		if (savedFetchResults == nil) {
			NSLog(@"%@", savedError);
		}
		[self.savedMegafauna removeAllObjects];
		[self.savedMegafauna addObjectsFromArray:savedFetchResults];
	}
	[self.tableView reloadData];
}

#pragma mark ExternalMethods
- (void)loadMegafaunaList{
	NSString *jsonString = [[[NSString alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:LIST_MFOW_URL]] encoding:NSUTF8StringEncoding] autorelease];
	self.listOfMegafauna = [jsonString JSONValue];
	[self.tableView reloadData];
}

#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if(self.listOfMegafauna == nil)
		return 1;
	if(allMegafauna == YES){
		return [self.listOfMegafauna count];
	}
	else{
		return [self.savedMegafauna count];
	}
}

// Display the cell for a megafauna of the week.  Differs in how it loads whether it was from the Internet or CoreData.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   static NSString *ListOfMegafaunaCellIdentifier = @"ListOfMegafaunaCell";
	ListOfMegafaunaOfWeekTableViewCell * cell = (ListOfMegafaunaOfWeekTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ListOfMegafaunaCellIdentifier];
   if(cell == nil) cell = [[[ListOfMegafaunaOfWeekTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ListOfMegafaunaCellIdentifier] autorelease];
	if(allMegafauna == YES){
		if(self.listOfMegafauna == nil){
			cell.nameLabel.text = @"No Internet connection.";
			return cell;
		}
      [ListOfMegafaunaOfWeekTableViewCell fillCell:cell withAllMegafauna:[self.listOfMegafauna objectAtIndex:indexPath.row]];
	}
	else{
		[ListOfMegafaunaOfWeekTableViewCell fillCell:cell withSavedMegafauna:[self.savedMegafauna objectAtIndex:indexPath.row]];
	}
   return cell;
}

#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if(allMegafauna){
		NSDictionary *info = [self.listOfMegafauna objectAtIndex:indexPath.row];
		[delegate megafaunaClicked:[NSNumber numberWithInt:[[info objectForKey:@"id"] intValue]]];
	}
	else{
		[delegate savedMegafaunaClicked:[self.savedMegafauna objectAtIndex:indexPath.row]];
	}
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
   return !allMegafauna;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
   if (editingStyle == UITableViewCellEditingStyleDelete) {
      [[[MarineFetcher sharedInstance] managedObjectContext] deleteObject:[self.savedMegafauna objectAtIndex:indexPath.row]];
		NSError *saveError;
		[[[MarineFetcher sharedInstance] managedObjectContext] save:&saveError];
		[self.savedMegafauna removeObjectAtIndex:indexPath.row];
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
   }  
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
	cell.backgroundColor = [UIColor clearColor];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
	return self.headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
	return 38;
}

@end

